package com.dftdla.server;

import com.dftdla.server.handler.*;
import com.dftdla.utils.ChannelUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 14501
 */
@Component
@Slf4j
public class ChatServer {
    /**
     * 数据解析工作和token鉴权
     */
    @Resource
    private WebSocketHandler WEB_SOCKET_HANDLER;
    @Resource
    private LoginRequestMessageHandler LOGIN_HANDLER;
    @Resource
    private ChatRequestMessageHandler CHAT_HANDLER;
    @Resource
    private GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER;
    @Resource
    private GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER;
    @Resource
    private GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER;
    @Resource
    private GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER;
    @Resource
    private GroupChatRequestMessageHandler GROUP_CHAT_HANDLER;
    @Resource
    private QuitHandler QUIT_HANDLER;
    @Resource
    private ElseMessageHandler ELSE_HANDLER;

    private Integer port = 8000;

    public void run(){
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup workers = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(boss,workers)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel nsc) throws Exception {
                            //空闲检测，检查连接是否正常，读写或空闲时间异常检查
                            //60s内如果没有数据接收，会触发一个事件
                            //配合客户端进行心跳检测，方式失效连接占用资源
                            nsc.pipeline().addLast(new IdleStateHandler(600, 0, 0));

                            //可同时作为入站和出站处理器
                            nsc.pipeline().addLast(new ChannelDuplexHandler() {

                                @Override
                                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                    IdleStateEvent e = (IdleStateEvent) evt;
                                    //当读空闲超时
                                    if (e.state() == IdleState.READER_IDLE) {
                                        log.warn("已经600S没有读到数据了！关闭连接！");
                                        ChannelUtils.close(ctx.channel());
                                    }
                                    super.userEventTriggered(ctx, evt);
                                }
                            });

                            nsc.pipeline().addLast(new HttpServerCodec())
                                    //大数据流支持
                                    .addLast(new ChunkedWriteHandler())
                                    //对http消息做聚合操作，会产生两个对象：FullHttpRequest和FullHttpResponse
                                    .addLast(new HttpObjectAggregator(1024 * 64))
                                    //ws支持
                                    .addLast(new WebSocketServerProtocolHandler("/"));

                            //指令解析
                            nsc.pipeline().addLast(WEB_SOCKET_HANDLER)

                                    //从本地模式改为在线模式
                                    //需要添加新指令时，创建一个新的Message子类，然后在此处添加对应的Handler
                                    .addLast(LOGIN_HANDLER)
                                    .addLast(CHAT_HANDLER)
                                    .addLast(GROUP_CREATE_HANDLER)
                                    .addLast(GROUP_JOIN_HANDLER)
                                    .addLast(GROUP_MEMBERS_HANDLER)
                                    .addLast(GROUP_QUIT_HANDLER)
                                    .addLast(GROUP_CHAT_HANDLER)
                                    .addLast(QUIT_HANDLER)

                                    //服务器不处理的指令
                                    .addLast(ELSE_HANDLER);
                        }
                    });
            Channel channel = bootstrap.bind(port).sync().channel();
            log.info("Netty Running ...");
            log.info("Netty started on port(s): {}",port);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Server Error ",e);
        } finally {
            boss.shutdownGracefully();
            workers.shutdownGracefully();
        }
    }
}
